/*
    created: 2023/4/12
    filename: listqueue.c
    author: 李东霖
    purpose：带头结点链队列的实现 
*/

#include"listqueue.h"
// 操作
//初始化 失败返回NULL 成功返回一个LinkQueue*
LinkQueue* InitQueue1()
{
    PListQueue q = (PListQueue)malloc(sizeof(LinkQueue));
    LNode *head = (LNode*)malloc(sizeof(LNode));
    if(q == NULL || head == NULL) return NULL;
    q->front = q->rear = head;
    head->next = NULL;
    return q;
}
//初始化    失败q=NULL 成功q=LinkQueue*  返回值 -1-存在p 0-失败 1-成功
int InitQueue2(PListQueue *q)
{
    if(*q != NULL) return -1;
    *q = (PListQueue)malloc(sizeof(LinkQueue));
    LNode *head = (LNode*)malloc(sizeof(LNode));
    if(*q == NULL || head == NULL) return 0;
    (*q)->front = (*q)->rear = head;
    head->next =NULL;
    return 1;
}
//销毁队列  
void DestroyQueue(PListQueue *q)
{
    if(*q == NULL) return;
    LNode* p = (*q)->front;
    LNode* del; 
    while(p != NULL)
    {
        del = p;
        p = p->next;
        free(del);
    }
    free(*q);
    *q = NULL;

}
//清空队列  
void ClearQueue(PListQueue q)
{
    if(q == NULL || q->front == NULL) return;
    LNode* p = q->front->next;
    LNode* del;
    while(p != NULL)
    {
        del = p;
        p = p->next;
        free(del);
    }
    q->rear = q->front;
    q->front->next = NULL;
}
//判断队列是否为空  返回值：-1-传入空指针 0-非空 1-空
int QueueEmpty(PListQueue q)
{
    if(q == NULL) return -1;
    if(q->front == q->rear) return 1;
    return 0;
}
//入队 返回值：-1-传入空指针 0-失败 1-成功
int enQueue(PListQueue q,ElemType *e)
{
    if(q == NULL|| q->front == NULL ||e == NULL) return -1;
    LNode* temp = (LNode*)malloc(sizeof(LNode));
    if(temp == NULL) return 0;
    memcpy(&temp->data,e,sizeof(ElemType));
    temp->next = NULL; 
    q->rear->next = temp;
    q->rear = temp;
    return 1;
} 
//出队 -1-传入空指针 0-失败 1-成功
int deQueue(PListQueue q,ElemType *e)
{
    if(q == NULL|| q->front == NULL || e == NULL) return -1;
    if(1 == QueueEmpty(q)) return 0;
    LNode* temp = q->front->next;
    memcpy(e,&temp->data,sizeof(ElemType));
    q->front->next = q->front->next->next;
    //如果你删除的是最后一个元素，那么重置rear
    if(q->rear == temp) 
    {
        printf("最后一个元素\n");
        q->rear =q->front;    
    } 
    free(temp);
    return 1;
}

//得到队头 -1-传入空指针 0-失败 1-成功
int GetHeadQueue(PListQueue q,ElemType *e)
{
    if(q == NULL|| q->front == NULL || e == NULL) return -1;
    if(1 == QueueEmpty(q)) return 0;
    LNode* temp = q->front->next;
    memcpy(e,&temp->data,sizeof(ElemType));
    return 1;
}
//得到队列的长度 -1-传入空指针 >=0 队列长度  
int LengthQueue(PListQueue q)
{
    if(q == NULL || q->front == NULL) return -1;
    int loca = 0;
    LNode* p = q->front;
    while(p->next != NULL)
    {
        ++loca;
        p = p->next;
    } 
    return loca;

} 

//打印队列  
void DispQueue(PListQueue q)
{
    if(q == NULL || q->front == NULL) return;
    LNode* p = q->front->next;
    while(p != NULL)
    {
        printf("%d  ",p->data);
        p = p->next;
    }     
}
